export function drawLine(
  ctx: CanvasRenderingContext2D,
  x0: number,
  y0: number,
  x1: number,
  y1: number
) {
  ctx.beginPath()
  ctx.moveTo(Math.floor(x0) + 0.5, Math.floor(y0) + 0.5)
  ctx.lineTo(Math.floor(x1) + 0.5, Math.floor(y1) + 0.5)
  ctx.closePath()
  ctx.stroke()
}

// export function drawLine(ctx: CanvasRenderingContext2D, x0: number, y0: number, x1: number, y1: number) {
//   ctx.beginPath()
//   ctx.moveTo(x0, y0)
//   ctx.lineTo(x1, y1)
//   ctx.closePath()
//   ctx.stroke()
// }

export function getPosY(t: number, t0: number, t1: number, y: number, h: number): number {
  return ((t0 - t) * h) / (t1 - t0) + h + y
}

function drawRoundRectPath(
  cxt: CanvasRenderingContext2D,
  width: number,
  height: number,
  radius: number
) {
  cxt.beginPath()
  // 从右下角顺时针绘制，弧度从0到1/2PI
  cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2)

  // 矩形下边线
  cxt.lineTo(radius, height)

  // 左下角圆弧，弧度从1/2PI到PI
  cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI)

  // 矩形左边线
  cxt.lineTo(0, radius)

  // 左上角圆弧，弧度从PI到3/2PI
  cxt.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2)

  // 上边线
  cxt.lineTo(width - radius, 0)

  // 右上角圆弧
  cxt.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2)

  // 右边线
  cxt.lineTo(width, height - radius)
  cxt.closePath()
}

/** 该方法用来绘制一个有填充色的圆角矩形
 *@param cxt:canvas的上下文环境
 *@param x:左上角x轴坐标
 *@param y:左上角y轴坐标
 *@param width:矩形的宽度
 *@param height:矩形的高度
 *@param radius:圆的半径
 *@param fillColor:填充颜色
 **/
export function fillRoundRect(
  cxt: CanvasRenderingContext2D,
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number
) {
  // 圆的直径必然要小于矩形的宽高
  if (2 * radius > width || 2 * radius > height) {
    return
  }

  cxt.save()
  cxt.translate(x, y)
  // 绘制圆角矩形的各个边
  drawRoundRectPath(cxt, width, height, radius)
  cxt.fill()
  cxt.restore()
}

/** 该方法用来绘制圆角矩形
 *@param cxt:canvas的上下文环境
 *@param x:左上角x轴坐标
 *@param y:左上角y轴坐标
 *@param width:矩形的宽度
 *@param height:矩形的高度
 *@param radius:圆的半径
 *@param lineWidth:线条粗细
 *@param strokeColor:线条颜色
 **/
export function strokeRoundRect(
  cxt: CanvasRenderingContext2D,
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number
) {
  // 圆的直径必然要小于矩形的宽高
  if (2 * radius > width || 2 * radius > height) {
    return
  }

  x = Math.floor(x)
  y = Math.floor(y)
  height = Math.floor(height)

  cxt.save()
  cxt.translate(x + 0.5, y + 0.5)
  // 绘制圆角矩形的各个边
  drawRoundRectPath(cxt, width, height, radius)
  cxt.stroke()
  cxt.restore()
}
